<template>
	<div class="routinesuperadmin">
		<el-card>
			<template #header>
				<div class="card-header clearfix">
					<span class="headerTitle">管理员列表</span>
					<div class="floatRight">
						<el-button type="primary" v-if="isAuthBtn('add')" @click="onColumnCzBtn({key:'add',data:''})"><i class="fa fa-send"></i>新增管理员</el-button>
					</div>
				</div>
			</template>
			<div style="margin-bottom:10px;">
				<div class="k-disply-inline-block" style="margin-right:10px;" v-if="state.pageInfo.heard.status.length>0">
					<el-select
						v-model="state.status"
						:multiple="false"
						placeholder="Select"
						style="width: 100px"
					>
						<el-option
						v-for="item,index in state.pageInfo.heard.status"
						:key="index"
						:label="item.title"
						:value="item.key"
						/>
					</el-select>
				</div>
				<div class="k-disply-inline-block" style="margin-right:10px;" v-if="state.pageInfo.heard.gender.length>0">
					<el-select
						v-model="state.gender"
						:multiple="false"
						placeholder="Select"
						style="width: 100px"
					>
						<el-option
						v-for="item,index in state.pageInfo.heard.gender"
						:key="index"
						:label="item.title"
						:value="item.key"
						/>
					</el-select>
				</div>
				<div class="k-disply-inline-block" style="margin-right:10px;" v-if="state.pageInfo.heard.role.length>0">
					<el-select
						v-model="state.role"
						:multiple="false"
						placeholder="Select"
						style="width: 100px"
					>
						<el-option
							v-for="item,index in state.pageInfo.heard.role"
							:key="index"
							:label="item.title"
							:value="item.key"
						/>
					</el-select>
				</div>
				<div class="k-disply-inline-block" style="margin-right:10px;" v-if="state.pageInfo.heard.search.length>0">
					<el-input
						v-model="state.key"
						placeholder="请输入关键词查询"
						clearable
					>
						<template #prepend>
							<el-select
								v-model="state.name"
								:multiple="false"
								placeholder="请选择"
								style="width: 100px"
							>
								<el-option
									v-for="item,index in state.pageInfo.heard.search"
									:key="index"
									:label="item.title"
									:value="item.key"
								/>
							</el-select>
						</template>
					</el-input>
				</div>
				<el-button style="margin-left:10px;" @click="chaxunBtn">查找</el-button>
				<el-button type="primary" size="default" @click="state.loginIp='';getAdminList();" v-if="state.loginIp">清除IP条件</el-button>
			</div>
			<div>
				<Table
					ref="tableRef"
					v-bind="state.tableData"
					class="table-demo"
					@pageChange="onTablePageChange"
					@sortHeader="onSortHeader"
					@columnCzBtn="onColumnCzBtn"
					@columnClick="onColumnClick"
				/>
			</div>
		</el-card>
		<!-- 修改弹窗 -->
		<el-dialog
			v-model="state.dtShow"
			:title="state.detailData.type=='add'?'新增管理员':'修改管理员'"
			center
		>
			<div>
				<el-form :model="state.detailData" ref="detailDataRef" :rules="rules" label-width="120px" status-icon>
					<!-- 新增管理员 -->
					<div v-if="state.detailData.type=='add'">
					</div>
					<!-- 修改管理员 -->
					<div v-else>

					</div>
					<el-form-item label="请选择用户" v-if="state.detailData.type=='add'" prop="uid">
						<el-select
							v-model="state.detailData.uid"
							:multiple="false"
							filterable
							remote
							clearable
							reserve-keyword
							placeholder="请输入昵称进行搜索"
							:remote-method="getUserList"
							:loading="state.userLoading"
						>
							<el-option
							v-for="item in state.userList"
							:key="item.uid"
							:label="item.nickName"
							:value="item.uid"
							/>
						</el-select>
					</el-form-item>
					<el-form-item label="头像" prop="uname" v-if="state.detailData.type=='editor'">
						<div class="selectImg">
							<el-image style="width: 100%;height: 100%;" fit="cover" :src="state.detailData.avatar">
								<template #error>
									<div style="line-height: 150px;text-align: center;">
										暂无图片
									</div>
								</template>
							</el-image>
							<div class="imgBtn">
								<i class="fa fa-eye" v-if="state.detailData.avatar"  @click="selectImgBtn('eye')"></i>
								<i class="fa fa-trash-o selectDel" v-if="state.detailData.avatar"  @click="selectImgBtn('del')"></i>
								<i class="fa fa-file-image-o" v-if="!state.detailData.avatar" @click="selectImgBtn('select')"></i>
							</div>
						</div>
					</el-form-item>
					<el-form-item label="用户名" prop="uname" v-if="state.detailData.type=='editor'">
						{{state.detailData.uname}}
					</el-form-item>
					<el-form-item label="用户昵称" prop="nickName" v-if="state.detailData.type=='editor'">
						<el-input v-model="state.detailData.nickName" clearable />
					</el-form-item>
					<el-form-item label="性别" prop="gender" v-if="state.detailData.type=='editor'">
						<el-radio-group v-model="state.detailData.gender">
							<el-radio label="0"  border>男</el-radio>
							<el-radio label="1"  border>女</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="手机号码" prop="phone" v-if="state.detailData.type=='editor'">
						<el-input v-model="state.detailData.phone" clearable />
					</el-form-item>
					<el-form-item label="邮箱" prop="email" v-if="state.detailData.type=='editor'">
						<el-input v-model="state.detailData.email" clearable />
					</el-form-item>
					<el-form-item label="QQ号" prop="qq" v-if="state.detailData.type=='editor'">
						<el-input v-model="state.detailData.qq" clearable />
					</el-form-item>
					<el-form-item label="微信号" prop="wx" v-if="state.detailData.type=='editor'">
						<el-input v-model="state.detailData.wx" clearable />
					</el-form-item>
					<el-form-item label="用户状态" prop="status" v-if="state.detailData.type=='editor'">
						<el-radio-group v-model="state.detailData.status">
							<el-radio label="0"  border>正常</el-radio>
							<el-radio label="1"  border>禁用</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="密码" prop="password" v-if="state.detailData.type=='editor'">
						<div>
							<el-input type="password" v-model="state.detailData.password" clearable show-password	  />
							<div>不填不修改</div>
						</div>
					</el-form-item>
					<el-form-item label="请选择权限" prop="role">
						<el-select
							v-model="state.detailData.role"
							:multiple="false"
							filterable
							remote
							clearable
							reserve-keyword
							placeholder="请输入权限名称进行搜索"
							:remote-method="getRoleList"
							:loading="state.roleLoading"
						>
							<el-option
								v-for="item in state.roleList"
								:key="item.role_id"
								:label="item.role_name"
								:value="item.role_key"
								:disabled="isRoleBtn(item.role_key)"
							/>
						</el-select>
					</el-form-item>
				</el-form>
			</div>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="state.dtShow = false;state.btnloading=false;">取消</el-button>
					<el-button type="primary" @click="queding" :loading="state.btnloading" :disabled="state.btnloading">确定</el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog v-model="imageShow">
			<img style="width:100%;" :src="imageUrl" alt="Preview Image" />
		</el-dialog>
		<!--图片弹窗-->
		<el-dialog
			v-model="state.selectImgShow"
			title="选择图片"
			center
			width="80%"
			append-to-body
		>
			<Accessory type="1" @select="imgSelectBtn" ></Accessory>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { toRefs,ref, reactive,onMounted, defineComponent ,defineAsyncComponent} from 'vue';
import { useRouter } from 'vue-router'
import { userApi } from '/@/api/user';
import { pageInfo } from '/@/api';
import { ElNotification, ElMessage ,ElMessageBox ,FormRules,ElTree} from 'element-plus'
import { isModification } from '/@/utils/kingmin';//去重

// 引入组件
const Table = defineAsyncComponent(() => import('/@/components/table/index.vue'));
const Accessory= defineAsyncComponent(() => import('/@/components/accessory/index.vue'));
const imageUrl = ref('')
const imageShow = ref(false)
// 定义变量内容
const tableRef = ref<RefType>();

const detailDataRef=ref();

const router = useRouter();

const state = reactive({
	roleBtn:router.currentRoute.value.meta.roleBtn,
	loading:true,
	tbloading:true,
	btnloading:false,
	dataList:[],
	pages: {
        isAll: false,
        pageCount: 0,
        pageSize: 10,
        recordCount: 0,
        pno: 1
	  },
	pageInfo:{
		tbhdList:[],
		heard:{
			status:[],
			gender:[],
			search:[],
			role:[],
		}
	},
	details:"",
	status:"",
	gender:"",
	name:"",
	key:"",
	orderBy:"",
	role:"",
	loginIp:"",
	tableData:{
		data: [],// 列表数据（必传）
		// 表头内容（必传，注意格式）
		header: [],
		// 配置项（必传）
		config: {
			total: 0, // 列表总数
			loading: true, // loading 加载
			isBorder: false, // 是否显示表格边框
			isSerialNo: false, // 是否显示表格序号
			isSelection: true, // 是否显示表格多选
			isExcel: true, // 是否可以导出
			excelName:"管理员列表"
		},
		btn:[]
	},
	czBtn:["editor","role","del"],
	dtShow:false,
	detailData:{
		type:"add",
		uid:"",
		uname:"",
		nickName:"",
		phone:"",
		avatar:"",
		gender:0,
		email:"",
		qq:"",
		wx:"",
		role:"ordinary",
		status:"",
		password:""
	},
	userList:[],
	originalData:{},
	userLoading:true,
	roleList:[],
	roleLoading:true,
	selectImgShow:false,
});
const rules = reactive<FormRules>({
	nickName: [
		{ required: true, message: '请输入用户昵称', trigger: 'blur' },
		{ min: 3, max:12, message: '最少4个字符,最多12个字符', trigger: 'blur' },
	],
	uid: [
		{ required: true, message: '必须确定要操作的用户', trigger: ['blur', 'change'] },
	],
	phone: [
		{ required: true, message: '请输入手机号码', trigger: 'blur' },
		{ min: 3, max:12, message: '最少4个字符,最多12个字符', trigger: 'blur' },
	],
	email: [
		{ required: true, message: '请输入邮箱', trigger: 'blur' },
		{ type: 'email', message: '输入的邮箱格式不正确', trigger: ['blur', 'change'], },
	],
	role: [
		{ required: true, message: '请选择用户权限', trigger: ['blur', 'change'] },
	],
	status: [
		{ required: true, message: '请选择角色权限', trigger: 'blur' },
	]
	
});
const imgSelectBtn = (item) => {
	for(let p of item){
		state.detailData.avatar=p.url;
	}
	quxiaoSelectBtn('img');
};
const quxiaoSelectBtn = (item) => {
	if(item=='img'){
		state.selectImgShow=false;
	}
	
};
const selectImgBtn=(e)=>{
	if(e=="eye"){
		imageUrl.value = state.detailData.avatar
  		imageShow.value = true
	}
	if(e=="del"){
		state.detailData.avatar="";
	}
	if(e=="select"){
		state.selectImgShow=true;
	}
};

const isRoleBtn=(key:string)=>{
	let rt=false;
	if(key=='admin'){
		rt=true;
	}
	if(state.detailData.type=="add"){
		if(key=='ordinary'){
			rt=true;
		}
	}
	return rt;
}
// 获取权限列表
function getRoleList(query: string){
	state.roleLoading=true;
	let dt={
		pages:{
			pno:1,
			pageSize:30,
		},
		data:{
			key:query,
			name:"role_name",
		}
	}
	userApi("roleList",dt).then(res=>{
		state.roleList=res.list;
		state.roleLoading=false;
	})
};
// 获取用户列表
function getUserList(query: string){
	state.userLoading=true;
	let dt={
		pages:{
			pno:1,
			pageSize:30,
		},
		data:{
			key:query,
			isAdmin:true
		}
	}
	userApi("userList",dt).then(res=>{
		state.userList=res.list;
		state.userLoading=false;
	})
};
// 确定按钮
const queding=()=>{
	detailDataRef.value.validate((valid) => {
		if (valid) {
			// console.log(state.detailData)
			// 修改
			let data=JSON.parse(JSON.stringify(state.detailData));
			state.btnloading=true;
			let dt={};
			if(state.detailData.type=='editor'){
				dt=isModification(data,state.originalData);
				// let dt=state.detailData;
				if(Object.values(dt).length>0){
					dt.uid=state.detailData.uid;
				}else{
					ElMessage({message:'没有要修改的数据',type:"warning"});
					state.dtShow=false;
					state.btnloading=false;
					return false;
				}
				// console.log(dt)
			}else{
				// addDataFun(data);
				dt.uid=state.detailData.uid;
				dt.role=state.detailData.role;
				dt.type="add";
			}			
			upDataFun(dt);
		}else{
			ElMessage({message:'请检查数据,有必填项未填写',type:"warning"});
		}
	})
}
const upDataFun=(dt:object)=>{
	if(!dt){
		ElMessage.error('修改的数据为空');
		return false;
	}
	userApi('upAdminDetail',dt).then(res=>{
		// console.log(res)
		ElMessage({message:res.msg?res.msg:"操作成功",type:"success"});
		state.dtShow=false;
		state.btnloading=false;
		getAdminList(state.pages.pno);
	})
	.catch(res=>{
		if(res.code!=450000){
			ElMessageBox.confirm(res.msg, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
			.then(() => {})
			.catch(() => {});
			state.btnloading=false;
		}
	})
}
const chaxunBtn=()=>{
	//  console.log(state.selectTime)
	getAdminList();
}
// 表单点击回调
const onColumnClick = (row: EmptyObjectType) => {
	if(row.key=='sort'){
		state.orderBy={
			order:row.data.order,
			prop:row.data.prop
		}
		getAdminList();
	}
	if(row.key=='link'){
		if(row.item.prop=='login_ip'){
			state.loginIp=row.data.login_ip;
			getAdminList();
		}
	}
	// getTableData();
};
// 表单操作回调
const onColumnCzBtn = (row: EmptyObjectType) => {
	// ElMessage.success(`删除${row.name}成功！`);
	// console.log(row)
	if(row.key=='editor'){
		state.originalData=row.data;
		state.originalData.type="editor";
		state.originalData.password="";
		state.detailData={
			type:"editor",
			uid:row.data.uid,
			uname:row.data.uname,
			nickName:row.data.nickName,
			phone:row.data.phone,
			avatar:row.data.avatar,
			gender:row.data.gender,
			email:row.data.email,
			qq:row.data.qq,
			wx:row.data.wx,
			role:row.data.role,
			status:row.data.status,
			password:""
		}
		getRoleList()
		state.dtShow=true;
		// console.log(state.detailData)
	}
	if(row.key=="add"){
		state.detailData={
			type:"add",
			uid:"",
			uname:"",
			nickName:"",
			phone:"",
			avatar:"",
			gender:0,
			email:"",
			qq:"",
			wx:"",
			role:"",
			status:"",
			password:""
		}
		getUserList();
		getRoleList();
		state.dtShow=true;
	}
	if(row.key=='role'){
		ElMessageBox.confirm(
			'确定取消管理员['+row.data.nickName+']的['+row.data.roleName+']权限吗?',
			'提示',
			{
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
			}
		)
		.then(() => {
			let dt={
				uid:row.data.uid,
				role:'ordinary'
			}
			if(row.data.create_by=='admin'){
				ElMessage({
					type: 'error',
					message: '不能操作系统创建的用户',
				})
			}else{
				upDataFun(dt);
			}
			//  console.log(dt)
		})
		.catch(() => {
			ElMessage({
				type: 'info',
				message: '取消',
			})
		})
	}
	if(row.key=='del'){
		ElMessageBox.confirm(
			'确定删除管理员['+row.data.nickName+']吗?',
			'提示',
			{
			confirmButtonText: '删除',
			cancelButtonText: '取消',
			type: 'warning',
			}
		)
		.then(() => {
			let dt={
				uid:row.data.uid,
				isdel:1
			}
			if(row.data.create_by=='admin'){
				ElMessage({
					type: 'error',
					message: '不能删除系统创建的用户',
				})
			}else{
				upDataFun(dt);
			}
			//  console.log(dt)
		})
		.catch(() => {
			ElMessage({
				type: 'info',
				message: '取消删除',
			})
		})
	}
	if(row.key=='delAll'){
		ElMessageBox.confirm(
			'确定删除所选择的管理员吗?',
			'提示',
			{
			confirmButtonText: '删除',
			cancelButtonText: '取消',
			type: 'warning',
			}
		)
		.then(() => {
			let list=[];
			for(let p of row.data){
				if(p.create_by=='admin'){
					ElMessage({
						type: 'error',
						message: '不能删除系统创建的角色',
					})
					return false;
				}
				list.push(p.uid);
			}
			let dt={
				//  console.log(dt)
				delList:list,
				isdel:1
			}
			upDataFun(dt);
		})
		.catch(() => {
			ElMessage({
				type: 'info',
				message: '取消删除',
			})
		})
	}
	// getTableData();
};
// 分页改变时回调
const onTablePageChange = (page: TableDemoPageType) => {
	// state.tableData.param.pageNum = page.pageNum;
	// state.tableData.param.pageSize = page.pageSize;
	// getTableData();
	state.pages.pageSize=page.pageSize;
	getAdminList(page.pno);
	// console.log(page)
};
// 拖动显示列排序回调
const onSortHeader = (data: TableHeaderType[]) => {
	state.tableData.header = data;
};
// 获取页面前置
const getpageInfo=()=>{
	pageInfo('member',{path:'admin'}).then(res=>{
		state.pageInfo=res;
		state.tableData.header=res.tbhdList;
		let btn=[];
		for(let p of state.czBtn){
			if(p!='role'){
				if(isAuthBtn(p)){
					btn.push(p);
				}
			}else{
				btn.push(p);
			}
		}
		state.tableData.btn=btn;
		getAdminList();
	})
}
// 获取管理员列表
const getAdminList=(pno:string|number)=>{
	state.tableData.config.loading =true;
	if(!pno){
		pno=1;
	}
	const dt={
		pages:{
			pno:pno,
			pageSize:state.pages.pageSize
		},
		data:{
			status:state.status,
			key:state.key,
			name:state.name,
			gender:state.gender,
			role:state.role,
			loginIp:state.loginIp,
			orderBy:state.orderBy,
		}
	};
	userApi('adminList',dt).then(res=>{
		state.dataList=res.list;
		state.tableData.data=res.list;
		state.tableData.config.total=res.pages.recordCount;
		state.pages=res.pages;
		state.tbloading=false;
		state.tableData.config.loading = false;
	})
}
// 权限判断
const isAuthBtn = (e) => {
	let auth=false;
	if(e){
		for(let p of state.roleBtn){
			if(p==e){
				auth=true;
			}
		}
	}
	return auth;
};
// 跳转
const tourl = (e) => {
	router.push(e);
};

onMounted(()=>{
      // 获取当前路由实例参数
    //   console.dir(router.currentRoute.value.query.id);
    //   console.dir(router.currentRoute.value.meta.roleBtn);
	  if(!isAuthBtn('index')){
		  router.push('/401');
	  }else{
		  //操作函数
		  getpageInfo();
	  }
})
</script>

<style scoped lang="scss">
	.routinesuperadmin{
		padding:5px;
	}
</style>
